/**
* Initialization of a static crowd
*/
kernel void initCrowd(	global float4 *agents,
						global float4 *velocity,
						global float2 *originalID,
						int mesh_width) {

    unsigned int x = get_global_id(0);
    unsigned int y = get_global_id(1);

    // calculate uv coordinates
    float u = (x % mesh_width) * (1280 / (float) mesh_width);
    float v = (y % mesh_width) * (800 / (float) mesh_width);

    // write output vertex
    agents[y*mesh_width + x]   = (float4)(u,    0.0f, v,    1.0f);
    velocity[y*mesh_width + x] = (float4)(0.1f, 0.0f, 0.0f, 0.0f);
    originalID[y*mesh_width + x] = (float2)(x, y);
}

// Moves the agents with basic seek rule
kernel void basicMovementKernel(global float4 *agents,
								global float4 *velocity,
								int mesh_width,
								float time){
	
	unsigned int x = get_global_id(0);
	unsigned int y = get_global_id(1);
	
	float4 pos = agents[y*mesh_width + x];
	float4 vel = velocity[y*mesh_width + x];
	
	float4 target;
	if(x == 0 && y == 0)
		target = agents[1];
	else
		target = agents[0];
		
	float4 target_offset = target - pos;
	float distance = length(target_offset);
	if(distance > 0.0f){
		target_offset = normalize(target_offset);
		if(distance < 20)
			target_offset *= 0.5*(distance/20);
		else
			target_offset *= 0.5;
	}
	
	if(x==0 && y == 0)
		vel -= target_offset;
	else
		vel += target_offset;
	vel = clamp(vel, -0.5, 0.5);
	pos += vel*time;
	
	agents[y*mesh_width + x] = pos;
	velocity[y*mesh_width + x] = vel;
}